package cn.z2huo.demo.spring.webmvc.controller.uploadfile;

import cn.z2huo.demo.spring.webmvc.entity.dto.No3CsvDataDTO;
import cn.z2huo.demo.spring.webmvc.entity.dto.api.multipartformdata.UploadFileReqDTO;
import cn.z2huo.demo.spring.webmvc.service.ReadCsvFileServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.validation.constraints.NotBlank;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

/**
 * <p>处理 contentType 为 multipart/form-data 格式的请求
 *
 * @author z2huo
 */
@Slf4j
@RequiredArgsConstructor
@RestController
@RequestMapping("/multipart")
public class MultipartFormDataController {

    private final ReadCsvFileServiceImpl readCsvFileService;

    private final ObjectMapper objectMapper;

    /**
     * <p>使用 POST 请求，上传一个文件，同时上传一个 json
     * @param file  文件
     * @return  成功
     */
    @PostMapping("/uploadFile")
    public String uploadFile(@RequestParam("file") MultipartFile file,
                             @RequestParam("jsonData") @NotBlank(message = "json 不能为空") String jsonData) {

        log.info("json data is {}", jsonData);
        try {
            UploadFileReqDTO uploadFileReqDTO = objectMapper.readValue(jsonData, UploadFileReqDTO.class);
            log.info("json data parse object is {}", uploadFileReqDTO);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        String name = file.getName();
        String contentType = file.getContentType();
        String originalFilename = file.getOriginalFilename();
        long size = file.getSize();
        log.info("upload file, " +
                "name: {}, " +
                "contentType: {}, " +
                "originalFilename: {}, " +
                "size: {}", name, contentType, originalFilename, size);

        if (!file.isEmpty()) {
            try {
                List<No3CsvDataDTO> data = readCsvFileService.readNo3CsvFile(file.getInputStream());
                No3CsvDataDTO first = data.getFirst();
                log.info("first data is {}", first);
            } catch (IOException e) {
                log.error("read csv file from request fail", e);
                throw new RuntimeException(e);
            }
        }
        return "upload file success";
    }

}
